package com.zx.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zx.domain.User;
import com.zx.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 注册学生信息管理系统

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        Map<String, Object> map = new HashMap<>();

        if(req.getParameter("username")==""||req.getParameter("password")==""){
            map.put("isExist", false);
            ObjectMapper om = new ObjectMapper();
            String s = om.writeValueAsString(map);
            resp.getWriter().print(s);

        }else{
            String name = req.getParameter("username");
            String password = req.getParameter("password");

            User user = new User(name, password);
            if(UserService.addUser(user)){
                map.put("isExist", true);
                ObjectMapper om = new ObjectMapper();
                String s = om.writeValueAsString(map);
                resp.getWriter().print(s);

            }else{
                map.put("isExist", false);
                ObjectMapper om = new ObjectMapper();
                String s = om.writeValueAsString(map);
                resp.getWriter().print(s);
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
